<template>
    <div class="app-container">
        <div class="search-container" ref="search">
            <el-form :model="form" inline size="default">
                <el-form-item label="关键字">
                    <el-input v-model="form.username" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item label="角色">
                    <el-select v-model="form.role_name" placeholder="请选择" clearable>
                        <el-option v-for="item in roleList" :key="item.id" :label="item.role_name"
                            :value="item.role_name">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="用户类型">
                    <el-select v-model="form.type_name" placeholder="请选择" clearable>
                        <el-option v-for="item in userTypeList" :key="item.id" :label="item.value" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">搜索</el-button>
                </el-form-item>
            </el-form>
        </div>
        <el-card shadow="never">
            <template #header>
                <el-button size="default" type="primary" @click="dialogFormVisible = true">添加</el-button>
                <el-button size="default" type="danger" @click="hanldeDelAll">批量删除</el-button>
            </template>
            <el-table :height="pageHeight + 'px'" @selection-change="handleSelectionChange"
                :data="tableData.filter((data) => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
                :default-sort="{ prop: 'id', order: 'descending' }" v-loading="tableDataLoading">
                <el-image src="/public/pwa_icons/192x192.png"></el-image>
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column label="用户名" prop="username"> </el-table-column>
                <el-table-column label="姓名" prop="name"> </el-table-column>
                <el-table-column label="角色" prop="role_name"> </el-table-column>
                <el-table-column label="用户类型" prop="type_name"> </el-table-column>
                <el-table-column label="手机号" prop="phone"> </el-table-column>
                <el-table-column label="区域" prop="region_name"> </el-table-column>
                <el-table-column label="所属单位" prop="unit_name"> </el-table-column>
                <el-table-column label="工作日志">
                    <template #default="scope">
                        <el-button type="primary" @click="showWorkLog(scope.row)" size="default">详情</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right">
                    <template #default="scope">
                        <el-button size="default" type="info" @click="lookDetails(scope.row)">查看</el-button>
                        <el-button size="default" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="block" style="margin-top: 15px">
                <!-- 分页 -->
                <el-pagination :current-page="pagination.page" :total="total" :page-size="pagination.size"
                    :page-sizes="pagination.sizes" :layout="pagination.layout" :hide-on-single-page="false"
                    class="pagination" background @size-change="onSizeChange" @current-change="onCurrentChange" />
            </div>
        </el-card>

        <!-- <div class="block">
        <el-pagination
          @current-change="handleCurrentChange"
          v-model:currentPage="tableDataInfo.page"
          :page-count="tableDataInfo.total_page"
          layout="prev, pager, next, jumper"
          :hide-on-single-page="true"
        >
        </el-pagination>
      </div> -->
        <el-dialog v-model="dialogFormVisible" width="70%" @closed="closeDialog" destroy-on-close
            :close-on-click-modal="false" :title="title">
            <el-form ref="childForm" :rules="rules" :model="formData" :disabled="disabled">
                <el-row>
                    <el-col :span="6" :offset="1">
                        <el-form-item label="用户名" prop="username">
                            <el-input :disabled="title == '编辑'" v-model="formData.username" :maxlength="18"
                                @input="test"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" :offset="1" v-if="title == '添加'">
                        <el-form-item label="密码" prop="password" :required="id ? true : false">
                            <el-input v-model="formData.password" show-password :maxlength="18"
                                oninput="value=value.replace(/[^a-zA-Z0-9_]/g,'')"
                                @blur="formData.password = $event.target.value"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" :offset="1" v-else>
                        <el-form-item label="密码">
                            <el-input v-model="formData.password" show-password :maxlength="18"
                                oninput="value=value.replace(/[^a-zA-Z0-9_]/g,'')"
                                @blur="formData.password = $event.target.value"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" :offset="1">
                        <el-form-item label="角色" prop="role_id">
                            <el-select v-model="formData.role_id" filterable placeholder="请选择">
                                <el-option v-for="item in roleList" :key="item.id" :label="item.role_name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" :offset="1">
                        <el-form-item label="用户类型" prop="type">
                            <el-select v-model="formData.type" filterable placeholder="请选择">
                                <el-option v-for="item in userTypeList" :key="item.id" :label="item.value"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="6" :offset="1">
                        <el-form-item label="姓名" prop="name">
                            <el-input v-model="formData.name"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" :offset="1">
                        <el-form-item label="性别" prop="sex">
                            <el-radio-group v-model="formData.sex">
                                <el-radio label="1">男</el-radio>
                                <el-radio label="2">女</el-radio>
                                <!-- <el-radio label="3">保密</el-radio> -->
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" :offset="1">
                        <el-form-item label="年龄" prop="age" :required="id ? true : false">
                            <el-input v-model="formData.age" oninput="value=value.replace(/[^\d]/g,'')"
                                @blur="formData.age = $event.target.value" :maxlength="2"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" :offset="1">
                        <el-form-item label="身份证" prop="card_no"><el-input
                                v-model="formData.card_no"></el-input></el-form-item>
                    </el-col>
                    <el-col :span="6" :offset="1">
                        <el-form-item label="手机号码" prop="phone">
                            <el-input v-model="formData.phone" oninput="value=value.replace(/[^\d]/g,'')"
                                :maxlength="11" @blur="formData.phone = $event.target.value"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" :offset="1">
                        <el-form-item label="岗位" prop="job">
                            <el-input v-model="formData.job"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col></el-col>
                    <el-col :offset="1">
                        <el-form-item label="状态" prop="status">
                            <el-switch v-model="formData.status" active-text="启用" inactive-text="禁用" :active-value="1"
                                :inactive-value="2"></el-switch>
                        </el-form-item>
                    </el-col>
                    <el-col :offset="1">
                        <el-form-item label="头像" prop="head_img">
                            <el-upload :action="upDataUrl + '/unit/upload/upload'" list-type="picture-card"
                                :headers="upLoadImgHeader" :data="upLoadImgData" :on-success="headImgUpSuccess"
                                limit="1" class="img" :before-remove="imgRemove" :on-change="imgChange"
                                accept=".jpg,.png,.jpeg" :file-list="imgFileList">
                                <i class="el-icon-plus"></i>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submitForm" v-if="!disabled">确 定</el-button>
                </span>
            </template>
        </el-dialog>
        <el-dialog v-model="workLogDialogVisible" width="60%">
            <el-table :data="workLogTableData" border style="width: 100%" height="500px">
                <el-table-column prop="id" label="ID" width="80"> </el-table-column>
                <el-table-column prop="unit_name" label="单位名称"> </el-table-column>
                <el-table-column prop="point_name" label="巡查点名称"> </el-table-column>
                <el-table-column prop="point_address" label="巡查点位置"> </el-table-column>
                <el-table-column prop="remark" label="备注"> </el-table-column>
                <el-table-column prop="add_time" label="巡查时间" :formatter="formatterDateTime"> </el-table-column>
            </el-table>
            <div class="block">
                <el-pagination @current-change="getWorkLog" v-model:currentPage="workLogInfo.page"
                    :page-count="workLogInfo.total_page" :total="workLogInfo.total"
                    layout="total,prev, pager, next, jumper" background>
                </el-pagination>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import storage from '@/util/storage'
import { ElMessage } from 'element-plus'
// 分页
import paginationMixin from '@/mixins/pagination'
export default {
    // 分页
    mixins: [paginationMixin],
    data() {
        return {
            title: '添加',
            searchValue: '',
            total: 0,
            disabled: false,
            dialogFormVisible: false,
            tableData: [],
            tableDataLoading: false,
            search: '',
            tableDataInfo: '',
            imgFileList: [],
            formData: {
                type: '',
                username: '',
                password: '',
                role_id: '',
                name: '',
                sex: '1',
                phone: '',
                head_img: '',
                card_no: '',
                age: '',
                job: '',
                qq: '',
                user_type: '',
                status: 1,
                unit_id: ''
            },
            societyList: [],
            rules: {
                username: [
                    { required: true, message: '请输入', trigger: 'blur' },
                    { min: 6, max: 18, trigger: 'blur', message: '用户名长度为6到18位' }
                ],
                password: [
                    { required: true, message: '请输入', trigger: 'blur' },
                    { min: 6, max: 18, trigger: 'blur', message: '密码长度为6到18位' }
                ],
                role_id: [{ required: true, message: '请选择', trigger: 'blur' }],
                name: [{ required: true, message: '请输入', trigger: 'blur' }],
                phone: [{ required: true, message: '请输入', trigger: 'blur' }],
                sex: [{ required: true, message: '请选择', trigger: 'blur' }],
                // head_img: [{ required: true, message: "请上传", trigger: "blur" }],
                user_type: [{ required: true, message: '请选择', trigger: 'blur' }],
                status: [{ required: true, message: '请选择', trigger: 'blur' }],
                unit_id: [{ required: true, message: '请选择', trigger: 'blur' }]
            },
            id: '',
            unit_id: '', //单位id
            sexLists: [
                { name: '男', id: 1 },
                { name: '女', id: 2 },
                { name: '保密', id: 3 }
            ],
            typeList: [],
            roleList: [],
            userTypeList: [],
            upDataUrl: import.meta.env.DEV ? '/proxy/' : import.meta.env.VITE_APP_API_BASEURL,
            upLoadImgData: {
                type: 'image'
            },
            form: {},
            workLogDialogVisible: false,
            workLogTableData: [],
            curWorkLogId: 0,
            workLogInfo: {},
            pageHeight: 0,
            ids: []
        }
    },
    mounted() {
        this.pageHeight = window.innerHeight - this.$refs.search.clientHeight - 280;
    },
    created() {
        this.$api.get('/unit/Setting/userType').then((res) => {
            this.userTypeList = res.data
        })
        // this.unit_id = this.$route.query.id;
        this.getDataList()
        this.getRoleList()
    },
    computed: {
        upLoadImgHeader() {
            return {
                'A-Token': this.$store.state.user.a_token,
                'U-Token': this.$store.state.user.u_token
            }
        }
    },
    methods: {
        handleSelectionChange(row) {
            this.ids = row.map(item => item.id)
        },
        hanldeDelAll() {
            if (this.ids.length == 0) {
                this.$message({
                    message: '请选择要删除的数据',
                    type: 'warning'
                });
                return
            }
            this.$confirm('你确定删除这些数据吗', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$api.post('/unit/YjUser/delYjUser', {
                    id: this.ids
                }).then(res => {
                    if (res.code == 200) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getDataList()
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        formatterDateTime(row, column, cellValue, index) {
            return this.$getDateTime(cellValue)
        },
        showWorkLog(row) {
            this.curWorkLogId = row.id
            this.workLogDialogVisible = true
            this.getWorkLog()
        },
        onSubmit() {
            this.getDataList()
        },
        test() {
            this.$forceUpdate()
        },
        getWorkLog(e) {
            this.$api
                .post('/unit/PatrolInfo/record', {
                    user_id: this.curWorkLogId,
                    page: e || 1,
                    rows: 10
                })
                .then((res) => {
                    this.workLogTableData = res.data.lists
                    this.workLogInfo = res.data
                })
        },
        //   图片
        imgChange() { },
        imgRemove() { },
        // 获取角色列表
        getRoleList() {
            this.$api
                .post('/unit/Config/roleList', {
                    type: 1
                })
                .then((res) => {
                    this.roleList = res.data.list
                })
        },
        headImgUpSuccess(e) {
            this.formData.head_img = e.data.result
        },
        closeDialog() {
            this.$refs.childForm.resetFields()
            this.formData = {
                type: '',
                username: '',
                password: '',
                role_id: '',
                name: '',
                sex: '1',
                phone: '',
                head_img: '',
                card_no: '',
                age: '',
                job: '',
                qq: '',
                user_type: '',
                status: 1,
                unit_id: ''
            }
            this.title = '添加'
            this.id = ''
            this.disabled = false
        },
        colTitle(row, column, cellValue, index, e) {
            if (e == 'danger_source') {
                let temp = ['', '公众', '监管机构', '维保单位', '社会单位']
                return temp[cellValue]
            } else if (e == 'status') {
                let temp = ['', '未整改', '待审核', '已整改']
                return temp[cellValue]
            }
        },
        getDataList(page) {
            this.tableDataLoading = true
            let pageNum = 1
            if (page) {
                pageNum = page
            }
            let query = {
                rows: this.pagination.size,
                page: this.pagination.page,
                keywords: this.searchValue,
                no_sub: 1,
                ...this.form
            }
            this.$api
                .post('/unit/YjUser/Lists', query)
                .then((res) => {
                    this.tableData = res.data.list
                    this.tableDataInfo = res.data
                    this.total = res.data.total
                })
                .finally(() => {
                    this.tableDataLoading = false
                })
        },
        // 搜索
        searchInputList() {
            this.getDataList()
        },
        handleEdit(index, row) {
            this.title = '编辑'
            this.id = row.id
            this.formData = JSON.parse(JSON.stringify(row))
            this.formData.sex = this.formData.sex + ''
            this.formData.unit_id = parseInt(this.formData.unit_id)
            this.dialogFormVisible = true
            if (row.head_img) {
                this.imgFileList = [{ url: this.upDataUrl + row.head_img }]
            }
        },
        // 查看详情
        lookDetails(row) {
            this.disabled = true
            this.id = row.id
            this.formData = JSON.parse(JSON.stringify(row))
            this.formData.sex = this.formData.sex + ''
            this.dialogFormVisible = true
            if (row.head_img) {
                this.imgFileList = [{ url: this.upDataUrl + row.head_img }]
            }
        },
        handleSizeChange(e) { },
        handleCurrentChange(e) {
            this.getDataList(e)
        },
        submitForm() {
            this.$refs.childForm.validate((valid) => {
                if (valid) {
                    let data = this.formData
                    if (this.id) {
                        data.id = this.id
                    }
                    this.$api.post('/unit/YjUser/Save', data).then((res) => {
                        if (res.code == 200) {
                            this.$message({
                                message: res.msg,
                                type: 'success'
                            })
                            this.getDataList()
                            this.dialogFormVisible = false
                        } else {
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            })
                        }
                    })
                } else {
                    ElMessage.error('请填写完整')
                    return false
                }
            })
        }
    }
}
</script>
<style scoped lang="scss">
.block {
    display: flex;
    justify-content: center;
}

.searchBox {
    display: flex;

    span {
        width: 50px;
        line-height: 40px;
        text-align: center;
    }

    .search {
        width: 30%;
    }
}

.searchMain {
    height: 80px;
}
</style>
